from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from django.conf import settings
from sqlalchemy import MetaData, create_engine, text


class HanaDB:
    """objects like Model.objects"""
    # 参考文档：https://docs.sqlalchemy.org/en/14/orm/declarative_tables.html
    metadata_obj = MetaData(schema="XXXXX")
    engine = create_engine(settings.HANA_URL, encoding='utf-8', echo=settings.HANA_ECHO, pool_size=0, max_overflow=-1)
    HanaBaseModel = declarative_base(engine, metadata=metadata_obj)
    Session = sessionmaker(engine, autocommit=True)

    def __init__(self):
        self.db_session = self.Session()

    def add(self, query):
        self.db_session.add(query)
        self.db_session.commit()
        self.db_session.close()

    @classmethod
    def fetchall_by_hana_sql(cls, sql, params=None):
        if params:
            cursor = cls.engine.execute(sql, params)
        else:
            cursor = cls.engine.execute(sql)
        datas = cursor.fetchall()
        return datas
